<?php
namespace backend\modules\wxbiz\controllers;

use Yii;
use backend\controllers\BjuiController;
use common\models\WxbizCorp;
use common\models\WxbizAgent;
use common\models\WxbizMenu;
use lib\wxbiz\Menu;

/**
 * WxbizAgentController implements the CRUD actions for WxbizAgent model.
 */
class MenuController extends BjuiController
{

    public function actionIndex()
    {
        $models = WxbizCorp::find()->with('agents')->all();
        return $this->render('index', [
            'models' => $models
        ]);
    }

    public function actionPublish($agent_id)
    {
        $return = Menu::Publish($agent_id);
        if ($return['errcode'] == 0) {
            return $this->ok('发布成功');
        } else {
            return $this->error($return['errmsg']);
        }
    }

    public function actionZtree($agent_id)
    {
        $models = WxbizMenu::find()->where([
            'agent_id' => $agent_id
        ])->all();
        return $this->render('ztree', [
            'models' => $models
        ]);
    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id)
        ]);
    }

    public function actionCreate()
    {
        $model = new WxbizMenu();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->data['id'] = yii::$app->db->getLastInsertID();
            return $this->ok('增加成功');
        } else {
            return $this->error(array_values($model->getFirstErrors()));
        }
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->data['id'] = $id;
            return $this->ok('更新成功');
        } else {
            return $this->error(array_values($model->getFirstErrors()));
        }
    }

    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->ok('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    protected function findModel($id)
    {
        if (($model = WxbizMenu::findOne($id)) !== null) {
            return $model;
        } else {
            return new WxbizMenu();
        }
    }
}
